<template>
  <div ref="chartRef" class="chart-wrapper" :class="{ loading: isLoading }">
    <LoadingAnimation v-if="isLoading" text="图表加载中..." />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import type { ECharts, EChartsOption } from 'echarts'
import { techTheme, techBlueTheme, techPurpleTheme } from '@/utils/echarts-theme'
import LoadingAnimation from './LoadingAnimation.vue'

const props = withDefaults(defineProps<{
  options: EChartsOption
  theme?: 'tech-dark' | 'tech-blue' | 'tech-purple'
  autoResize?: boolean
  loading?: boolean
}>(), {
  theme: 'tech-dark',
  autoResize: true,
  loading: false
})

const chartRef = ref<HTMLElement>()
let chartInstance: ECharts | null = null
const isLoading = ref(props.loading)

// 注册主题
echarts.registerTheme('tech-dark', techTheme)
echarts.registerTheme('tech-blue', techBlueTheme)
echarts.registerTheme('tech-purple', techPurpleTheme)

function initChart() {
  if (!chartRef.value) return

  // 销毁旧实例
  if (chartInstance) {
    chartInstance.dispose()
  }

  // 创建新实例
  chartInstance = echarts.init(chartRef.value, props.theme)
  chartInstance.setOption(props.options)

  // 自动 resize
  if (props.autoResize) {
    window.addEventListener('resize', handleResize)
  }
}

function handleResize() {
  chartInstance?.resize()
}

function updateChart() {
  if (chartInstance && props.options) {
    chartInstance.setOption(props.options, true)
  }
}

// 监听配置变化
watch(() => props.options, () => {
  updateChart()
}, { deep: true })

// 监听主题变化
watch(() => props.theme, () => {
  initChart()
})

// 监听加载状态
watch(() => props.loading, (val) => {
  isLoading.value = val
  if (chartInstance) {
    if (val) {
      chartInstance.showLoading({
        text: '加载中...',
        color: 'var(--color-primary)',
        textColor: 'var(--text-primary)',
        maskColor: 'rgba(10, 14, 39, 0.8)'
      })
    } else {
      chartInstance.hideLoading()
    }
  }
})

onMounted(async () => {
  await nextTick()
  initChart()
})

onUnmounted(() => {
  if (props.autoResize) {
    window.removeEventListener('resize', handleResize)
  }
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

// 暴露实例方法
defineExpose({
  getInstance: () => chartInstance,
  resize: () => chartInstance?.resize()
})
</script>

<style lang="scss" scoped>
.chart-wrapper {
  width: 100%;
  height: 100%;
  min-height: 300px;
  position: relative;
  
  &.loading {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
